package com.exp.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.exp.dto.UserInfDTO;
import com.exp.dto.UserPageQueryDTO;
import com.exp.mapper.DocumentInfMapper;
import com.exp.mapper.NoticeInfMapper;
import com.exp.mapper.UserInfMapper;
import com.exp.result.PageResult;
import com.exp.service.UserInfService;
import com.exp.dto.LoginDTO;
import com.exp.pojo.UserInf;
import com.exp.utils.Message;
import com.exp.vo.UserInfVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import java.util.*;

/**
* @author 王-自信
* @description 针对表【user_inf】的数据库操作Service实现
* @createDate 2024-11-18 20:52:05
*/
@Service
public class UserInfServiceImpl extends ServiceImpl<UserInfMapper, UserInf>
    implements UserInfService {

    @Autowired
    private UserInfMapper userInfMapper;
    @Autowired
    private DocumentInfMapper documentInfMapper;
    @Autowired
    private NoticeInfMapper noticeInfMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;

    // 检查当前密码是否正确


    /**
     * 登录
     */
    @Override
    public UserInf login(LoginDTO loginDTO) {
        String loginname = loginDTO.getLoginname();
        String password = loginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        UserInf userInf = userInfMapper.getByLoginname(loginname);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被禁用）
        if (userInf == null) {
            //账号不存在
            throw new RuntimeException(Message.ACCOUNT_NOT_FOUND);
        }

        //密码比对: 对前端传过来的明文密码进行md5加密处理
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(userInf.getPassword())) {
            //密码错误
            throw new RuntimeException(Message.PASSWORD_ERROR);
        }

        //3、返回实体对象
        return userInf;
    }

    /**
     * 分页查询
     */
    @Override
    public PageResult pageQuery(UserPageQueryDTO userPageQueryDTO) {
        System.out.println("service:"+userPageQueryDTO);
        // select * from employee limit 0,10
        PageHelper.startPage(userPageQueryDTO.getPage(), userPageQueryDTO.getPageSize());

        Page<UserInf> page = userInfMapper.pageQuery(userPageQueryDTO);

        long total = page.getTotal();

        List<UserInf> records = page.getResult();
        return new PageResult(total, records);
    }

    /**
     * 新增用户
     */
    @Override
    public UserInfVO save(UserInfDTO userInfDTO) {
        UserInf userInf = new UserInf();

        //对象属性拷贝
        BeanUtils.copyProperties(userInfDTO, userInf);

        //密码进行加密
        userInf.setPassword(DigestUtils.md5DigestAsHex(userInf.getPassword().getBytes()));

        // 从 Calendar 实例中获取当前时间
        //设置当前记录的创建时间
        userInf.setCreatedate(Calendar.getInstance().getTime());
        userInfMapper.insert(userInf);

        UserInfVO userInfVO = new UserInfVO();
        BeanUtils.copyProperties(userInf, userInfVO);
        return userInfVO;
    }

    @Override
    public void update(UserInfDTO userInfDTO) {
        UserInf userInf = new UserInf();
        BeanUtils.copyProperties(userInfDTO, userInf);
        userInfMapper.update(userInf);
    }



    @Override
    public void deleteBatch(List<Integer> ids) {
        //判断是否能够删除---是否被下载文档关联
        List<Integer> documentIds = userInfMapper.getDocumentIdsByUserIds(ids);
        System.out.println("关联下载文档id集合：" + documentIds);
        Set<String> docSet = new HashSet<>(); // 使用HashSet来存储不重复的用户名

        if (documentIds != null && !documentIds.isEmpty()) {
            System.out.println("----下载文档----");
            for (Integer id : documentIds) {
                Integer userId = documentInfMapper.selectById(id).getUserId();
                UserInf userInf = userInfMapper.selectById(userId);
                docSet.add(userInf.getLoginname()); // 将用户名添加到Set集合中
            }

            if (!docSet.isEmpty()) {
                // 将Set集合转换为字符串，用逗号分隔
                String doc = String.join(",", docSet);
                // 被关联了，不能删除
                throw new RuntimeException("用户" + doc + "被下载业务关联了，不能删除");
            }
        }

        //判断是否能够删除---是否被公告关联
        //根据用户id 集合 查询对应的公告id 集合
        List<Integer> noticeIds = userInfMapper.getNoticeIdsByUserIds(ids);
        System.out.println("公告id 集合" + noticeIds);
        Set<String> nocSet = new HashSet<>(); // 使用HashSet来存储不重复的用户名

        if (noticeIds != null && !noticeIds.isEmpty()) {
            System.out.println("----公告----");
            for (Integer id : noticeIds) {
                Integer userId = noticeInfMapper.selectById(id).getUserId();
                UserInf userInf = userInfMapper.selectById(userId);
                nocSet.add(userInf.getLoginname()); // 将用户名添加到Set集合中
            }
            if (!nocSet.isEmpty()) {
                // 将Set集合转换为字符串，用逗号分隔
                String noc = String.join(",", nocSet);
                // 被关联了，不能删除
                throw new RuntimeException("用户" + noc + "被公告业务关联了，不能删除");
            }
        }

        //删除数据
        for (Integer id : ids) {
            userInfMapper.deleteById(id);
        }
    }

    // 检查当前密码是否正确
    public boolean checkCurrentPassword(Integer id, String currentPassword) {
        UserInf user = userInfMapper.selectById(id);
        if (user != null) {
            return passwordEncoder.matches(currentPassword, user.getPassword());
        }
        return false;
    }

    // 更新密码
    @Transactional
    public boolean updatePassword(Integer id, String newPassword) {
        UserInf user = userInfMapper.selectById(id);
        if (user != null) {
            String encodedPassword = passwordEncoder.encode(newPassword);
            user.setPassword(encodedPassword);
            return userInfMapper.updateById(user) > 0;
        }
        return false;
    }

    @Override
    public UserInf getByUserId(Integer id) {
        return userInfMapper.getByUserId(id);
    }


}




